package demo02;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;


public class Test01 {
    public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
        Map<String, Object> map = Map.of("name", "Hanser", "age", 18, "address", "China");
        Person person = mapToObj(map, Person.class);
        System.out.println(person);
    }

    public static <T> T mapToObj(Map<String, Object> map, Class<T> clazz) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Field[] declaredFields = clazz.getDeclaredFields();
        T t = clazz.getConstructor().newInstance();
        for (Field declaredField : declaredFields) {
            if (map.containsKey(declaredField.getName())) {
                declaredField.setAccessible(true);
                declaredField.set(t, map.get(declaredField.getName()));
            }
        }
        return t;
    }


    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    static class Person implements Serializable {
        private String name;
        private Integer age;
        private String address;
    }
}
